<template>
	<view class="chartsBox">
		<view class="chartsTitle">
			<h4>产品销售业绩</h4>
		</view>

		<uni-datetime-picker ref="datetimePicker" :clear-icon="false" v-model="timeSelect" type="daterange"
			@change="datetimePickerChange" />

		<view class="chartsMain">
			<view v-if="nodata" class="noData">
				<image src="/static/imgs/data/noData.png"></image>
			</view>
			<view v-else class="charts-box" :style="{ height: chartsBoxHeight + 'rpx' }">
				<qiun-data-charts type="bar" tooltipFormat="tooltipDisplay0" :opts="opts" :chartData="chartData" />
			</view>
		</view>


	</view>
</template>

<script setup>
	import {
		ref,
		reactive,
		onMounted,
		defineProps,
		watch
	} from 'vue';

	import {
		onShow
	} from '@dcloudio/uni-app'

	import {
		homeGetSellProductAch,
		phoneStaGetPartnerProductAche
	} from '../../../utils/data';
	import {
		Logger
	} from 'sass';

	let datetimePicker = ref(null)

	let chartsBoxHeight = ref(null)

	const props = defineProps({
		staffOrPartnerSelect: Number
	})




	//日期选择器绑定的值
	let timeSelect = ref([])

	// =======================让日期选择器 初始值为： 本月的1号-本月的今天=======================//
	let getCurrentDate = () => {
		const dateObj = new Date();
		const year = dateObj.getFullYear(); // 获取当前年份
		const month = ("0" + (dateObj.getMonth() + 1)).slice(-2); // 获取当前月份，其中需要将月份加1，因为月份是从0开始计数的
		const day = ("0" + dateObj.getDate()).slice(-2); // 获取当前日期
		const timeSelectFirst = `${year}-${month}-01`
		const timeSelectSecond = `${year}-${month}-${day}`; // 格式化日期
		timeSelect.value = [timeSelectFirst, timeSelectSecond]
	}
	getCurrentDate()



	//日期选择器发生改变时
	let datetimePickerChange = (e) => {
		getServerData()
	}

	// =============================获取图表实例============================/
	const chartRef = ref(null)


	let chartData = ref({
		categories: [],
		series: []
	});

	let opts = reactive({
		timing: "easeOut",
		duration: 1000,
		rotate: false,
		rotateLock: false,
		color: ["#1890FF", "#91CB74", "#FAC858", "#EE6666", "#73C0DE", "#3CA272", "#FC8452", "#9A60B4", "#ea7ccc"],
		padding: [0, 0, 0, 0],
		fontSize: 9,
		fontColor: "#666666",
		dataLabel: true,
		dataPointShape: true,
		dataPointShapeType: "solid",
		touchMoveLimit: 60,
		enableScroll: false,
		enableMarkLine: false,
		legend: {
			show: true,
			position: "top",
			float: "right",
			padding: 5,
			margin: 5,
			backgroundColor: "rgba(0,0,0,0)",
			borderColor: "rgba(0,0,0,0)",
			borderWidth: 0,
			fontSize: 13,
			fontColor: "#666666",
			lineHeight: 11,
			hiddenColor: "#CECECE",
			itemGap: 10
		},
		xAxis: {
			boundaryGap: "justify",
			disableGrid: false,
			min: 0,
			axisLine: false,
			disabled: false,
			axisLineColor: "#CCCCCC",
			calibration: false,
			fontColor: "#666666",
			fontSize: 9,
			lineHeight: 20,
			marginTop: 0,
			rotateLabel: false,
			rotateAngle: 45,
			itemCount: 5,
			splitNumber: 3,
			gridColor: "#CCCCCC",
			gridType: "solid",
			dashLength: 4,
			gridEval: 1,
			scrollShow: false,
			scrollAlign: "left",
			scrollColor: "#A6A6A6",
			scrollBackgroundColor: "#EFEBEF",
			title: "",
			titleFontSize: 13,
			titleOffsetY: 0,
			titleOffsetX: 0,
			titleFontColor: "#666666",
			format: ""
		},
		yAxis: {
			disabled: false,
			disableGrid: false,
			splitNumber: 5,
			gridType: "solid",
			dashLength: 8,
			gridColor: "#CCCCCC",
			padding: 10,
			showTitle: false,
			data: []
		},
		extra: {
			bar: {
				type: "stack",
				width: 12,
				meterBorde: 1,
				meterFillColor: "#FFFFFF",
				activeBgColor: "#000000",
				activeBgOpacity: 0.08,
				seriesGap: 2,
				categoryGap: 3,
				barBorderCircle: false,
				linearType: "none",
				linearOpacity: 1,
				colorStop: 0
			},
			tooltip: {
				showBox: true,
				showArrow: true,
				showCategory: false,
				borderWidth: 0,
				borderRadius: 0,
				borderColor: "#000000",
				borderOpacity: 0.7,
				bgColor: "#000000",
				bgOpacity: 0.7,
				gridType: "solid",
				dashLength: 4,
				gridColor: "#CCCCCC",
				boxPadding: 3,
				fontSize: 13,
				lineHeight: 20,
				fontColor: "#FFFFFF",
				legendShow: true,
				legendShape: "auto",
				splitLine: true,
				horizentalLine: false,
				xAxisLabel: false,
				yAxisLabel: false,
				labelBgColor: "#FFFFFF",
				labelBgOpacity: 0.7,
				labelFontColor: "#666666"
			},
			markLine: {
				type: "solid",
				dashLength: 4,
				data: []
			}
		}
	})


	const staffName = ref([])
	const productNameArr = ref([])
	const allotAchArr = ref([])
	const series = ref([])

	const nodata = ref(false)

	let getServerData = () => {

		//获取登录账号的businessId
		let userinfo = JSON.parse(uni.getStorageSync('userinfo'))
		let businessId = userinfo.businessId

		if (props.staffOrPartnerSelect == 0) {

			homeGetSellProductAch('/home/getSellProductAch', {
				beginTime: timeSelect.value[0],
				endTime: timeSelect.value[1],
				businessId: businessId,
			}).then((res) => {
				successfullyConnected(res)
			})
		} else if (props.staffOrPartnerSelect == 1) {

			phoneStaGetPartnerProductAche('/phoneSta/getPartnerProductAche', {
				beginTime: timeSelect.value[0],
				endTime: timeSelect.value[1],
				businessId: businessId,
			}).then((res) => {
				successfullyConnected(res)
			})
		}

	}

	let successfullyConnected = (res) => {
		if (res.code == 200) {
			if (res.data.length) {
				nodata.value = false
				productNameArr.value.length = 0
				staffName.value.length = 0
				allotAchArr.value.length = 0
				series.value.length = 0
				for (let i = 0; i < res.data.length; i++) {
					productNameArr.value.push(res.data[i].productName)
					staffName.value.push(res.data[i].name)
				}
				productNameArr.value = [...new Set(productNameArr.value)]
				staffName.value = [...new Set(staffName.value)]

				// 设置二维数组来存储每个员工售卖每个产品的业绩
				for (let i = 0; i < staffName.value.length; i++) {
					allotAchArr.value[i] = []
					for (let j = 0; j < productNameArr.value.length; j++) {
						allotAchArr.value[i][j] = 0
					}
				}


				// 遍历数据，将每个员工售卖每个产品的业绩存入对应的数组中
				for (let i = 0; i < staffName.value.length; i++) {
					for (let j = 0; j < productNameArr.value.length; j++) {
						res.data.forEach(item => {
							if (item.productName == productNameArr.value[j] && item.name ==
								staffName.value[i]) {
								allotAchArr.value[i][j] = item.allotAch
							}
						})
					}
				}

				for (let i = 0; i < staffName.value.length; i++) {
					series.value[i] = {
						name: staffName.value[i],
						data: allotAchArr.value[i],
						format: 'hidden0'
					}
				}

				//根据series.value[0].data返回的数量 动态设置chartsBoxHeight盒子的高度
				if (series.value[0].data.length < 7) {
					chartsBoxHeight.value = 366
				} else if (series.value[0].data.length < 11) {
					chartsBoxHeight.value = 549
				} else if (series.value[0].data.length < 14) {
					chartsBoxHeight.value = 732
				} else if (series.value[0].data.length < 18) {
					chartsBoxHeight.value = 1098
				} else if (series.value[0].data.length < 22) {
					chartsBoxHeight.value = 1281
				} else {
					chartsBoxHeight.value = 1500
				}

				let result = {
					categories: productNameArr.value,
					series: series.value
				};
				chartData.value = JSON.parse(JSON.stringify(result));
			} else {
				nodata.value = true
			}

		}
	}







	// onMounted(() => {
	// 	getServerData()
	// })

	onShow(() => {
		if (datetimePicker.value) {
			datetimePicker.value.clear()
		}
		getCurrentDate()
		getServerData()
	})

	watch(() => props.staffOrPartnerSelect, (newCount, oldCount) => {
		if (datetimePicker.value) {
			datetimePicker.value.clear()
		}

		getCurrentDate()


		getServerData()

	})
</script>

<style scoped lang="scss">
	.chartsBox {
		width: 688rpx;
		// height: 515rpx;
		padding: 18rpx;
		background: white;
		margin: 14rpx 0;

		.chartsTitle {
			width: 100%;
			height: 46rpx;
			margin-bottom: 14rpx;

		}

		.chartsMain {
			width: 100%;
			height: 366rpx;
			overflow: auto;
			// height: 1066rpx;

			// background-color: #bfa;
			/* 请根据实际需求修改父元素尺寸，组件自动识别宽高 */
			.charts-box {
				width: 100%;
				height: 100%;
				// height: 1066rpx;
			}

			.noData {
				width: 100%;
				height: 100%;
				display: flex;
				justify-content: center;
				align-items: center;

				image {
					width: 400rpx;
					height: 100%;
				}
			}
		}
	}
</style>